package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.SysSingleQuestion;
import com.ruoyi.system.domain.SysStudentCertificate;
import com.ruoyi.system.domain.SysTestPaper;
import com.ruoyi.system.mapper.SysStudentCertificateMapper;
import com.ruoyi.system.mapper.SysTestPaperMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysStudentExamMapper;
import com.ruoyi.system.domain.SysStudentExam;
import com.ruoyi.system.service.ISysStudentExamService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 考试记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class SysStudentExamServiceImpl implements ISysStudentExamService 
{
    @Autowired
    private SysStudentExamMapper sysStudentExamMapper;

    @Autowired
    private SysTestPaperMapper sysTestPaperMapper;

    @Autowired
    private SysStudentCertificateMapper sysStudentCertificateMapper;

    /**
     * 查询考试记录
     * 
     * @param id 考试记录主键
     * @return 考试记录
     */
    @Override
    public SysStudentExam selectSysStudentExamById(Long id)
    {
        return sysStudentExamMapper.selectSysStudentExamById(id);
    }

    /**
     * 查询考试记录列表
     * 
     * @param sysStudentExam 考试记录
     * @return 考试记录
     */
    @Override
    public List<SysStudentExam> selectSysStudentExamList(SysStudentExam sysStudentExam)
    {
        return sysStudentExamMapper.selectSysStudentExamList(sysStudentExam);
    }

    @Override
    public List<SysStudentExam> selectSysStudentExamStudentList(SysStudentExam sysStudentExam) {
        sysStudentExam.setUserId(ShiroUtils.getUserId());
        return sysStudentExamMapper.selectSysStudentExamList(sysStudentExam);
    }

    /**
     * 新增考试记录
     * 
     * @param sysStudentExam 考试记录
     * @return 结果
     */
    @Override
    public int insertSysStudentExam(SysStudentExam sysStudentExam)
    {
        sysStudentExam.setCreateTime(DateUtils.getNowDate());
        return sysStudentExamMapper.insertSysStudentExam(sysStudentExam);
    }

    /**
     * 修改考试记录
     * 
     * @param sysStudentExam 考试记录
     * @return 结果
     */
    @Override
    public int updateSysStudentExam(SysStudentExam sysStudentExam)
    {
        sysStudentExam.setUpdateTime(DateUtils.getNowDate());
        return sysStudentExamMapper.updateSysStudentExam(sysStudentExam);
    }

    /**
     * 批量删除考试记录
     * 
     * @param ids 需要删除的考试记录主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentExamByIds(String ids)
    {
        return sysStudentExamMapper.deleteSysStudentExamByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除考试记录信息
     * 
     * @param id 考试记录主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentExamById(Long id)
    {
        return sysStudentExamMapper.deleteSysStudentExamById(id);
    }

    /**
     * 提交考试信息
     * @param sysStudentExam 作答信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examSubmit(SysStudentExam sysStudentExam) {
        // 获取考试信息
        Long id = sysStudentExam.getId();
        SysStudentExam studentExamInDB = this.selectSysStudentExamById(id);
        if (studentExamInDB.getStatus().equals("HAVE_TAKEN_THE_EXAM")) {
            throw new RuntimeException("考试已参与");
        }
        // 获取试卷信息
        SysTestPaper sysTestPaper = sysTestPaperMapper.selectSysTestPaperById(studentExamInDB.getTestPaperId());
        List<SysSingleQuestion> singleQuestionsInDB = JSON.parseArray(sysTestPaper.getExtendedField(), SysSingleQuestion.class);
        Map<Long, SysSingleQuestion> inDBMap = singleQuestionsInDB.stream().collect(Collectors.toMap(SysSingleQuestion::getId, Function.identity()));
        // 获取作答信息
        long grade = 0L;
        List<SysSingleQuestion> sysSingleQuestions = sysStudentExam.getSysSingleQuestions();
        for (SysSingleQuestion sysSingleQuestion : sysSingleQuestions) {
            SysSingleQuestion answerInDB = inDBMap.get(sysSingleQuestion.getId());
            if (Objects.equals(answerInDB.getAnswer(), sysSingleQuestion.getAnswer())) {
                grade = grade + Long.parseLong(answerInDB.getGrade());
            }
        }
        studentExamInDB.setEndTime(new Date());
        studentExamInDB.setStatus("HAVE_TAKEN_THE_EXAM");
        studentExamInDB.setScore(grade);
        this.updateSysStudentExam(studentExamInDB);
    }

    @Override
    public void zhengshuSave(SysStudentExam sysStudentExam) {
        // 查询考试信息
        Long id = sysStudentExam.getId();
        SysStudentExam inDB = this.selectSysStudentExamById(id);
        // 校验数据
        this.checkSysStudentCertificate(inDB);
        // 构造数据
        SysStudentCertificate sysStudentCertificate = new SysStudentCertificate();
        sysStudentCertificate.setCourseId(inDB.getCourseId());
        sysStudentCertificate.setCourseName(inDB.getCourseName());
        sysStudentCertificate.setDeptId(inDB.getDeptId());
        sysStudentCertificate.setDeptName(inDB.getDeptName());
        sysStudentCertificate.setUserId(inDB.getUserId());
        sysStudentCertificate.setUsername(inDB.getUsername());
        sysStudentCertificate.setFileUrl(sysStudentExam.getFileUrl());

        sysStudentCertificateMapper.insertSysStudentCertificate(sysStudentCertificate);
    }

    public void checkSysStudentCertificate(SysStudentExam inDB) {
        SysStudentCertificate sysStudentCertificate = new SysStudentCertificate();
        sysStudentCertificate.setCourseId(inDB.getCourseId());
        sysStudentCertificate.setUserId(inDB.getUserId());
        List<SysStudentCertificate> sysStudentCertificates = sysStudentCertificateMapper.selectSysStudentCertificateList(sysStudentCertificate);
        if (!CollectionUtils.isEmpty(sysStudentCertificates)) {
            throw new RuntimeException("证书已签发过，请勿重复颁发");
        }
    }
}
